// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/expression/boolean_mix.h>

namespace kumo::pollux::exec {
    namespace {
        /// Checks if bits in specified positions are all set, all unset or mixed.
        BooleanMix refineBooleanMixNonNull(
            const uint64_t *bits,
            const SelectivityVector &rows) {
            int32_t first = bits::findFirstBit(bits, rows.begin(), rows.end());
            if (first < 0) {
                return BooleanMix::kAllFalse;
            }
            if (first == rows.begin() && bits::isAllSet(bits, rows.begin(), rows.end())) {
                return BooleanMix::kAllTrue;
            }
            return BooleanMix::kMixNonNull;
        }
    } // namespace

    // Return a BooleanMix representing the status of boolean values in vector. If
    // vector contains a mix of true and false, extract the boolean values to a raw
    // buffer valuesOut. valuesOut may point to a raw buffer possessed by vector.
    // nullsOut remain unchanged if there is no null in vector. tempValues and
    // tempNulls may or may not be set by this function.
    BooleanMix getFlatBool(
        BaseVector *vector,
        const SelectivityVector &activeRows,
        EvalCtx &context,
        BufferPtr *tempValues,
        BufferPtr *tempNulls,
        bool mergeNullsToValues,
        const uint64_t **valuesOut,
        const uint64_t **nullsOut) {
        POLLUX_CHECK_EQ(vector->type_kind(), TypeKind::BOOLEAN);
        const auto size = activeRows.end();
        switch (vector->encoding()) {
            case VectorEncoding::Simple::FLAT: {
                auto values =
                        vector->as_unchecked<FlatVector<bool> >()->rawValues<uint64_t>();
                if (!values) {
                    return BooleanMix::kAllNull;
                }
                auto nulls = vector->raw_nulls();
                if (nulls && mergeNullsToValues) {
                    uint64_t *mergedValues;
                    BaseVector::ensure_buffer<bool>(
                        size, context.pool(), tempValues, &mergedValues);

                    // NOTE: false bit in 'nulls' indicate null.
                    bits::andBits(
                        mergedValues, values, nulls, activeRows.begin(), activeRows.end());

                    bits::andBits(
                        mergedValues,
                        activeRows.asRange().bits(),
                        activeRows.begin(),
                        activeRows.end());

                    *valuesOut = mergedValues;
                    return refineBooleanMixNonNull(mergedValues, activeRows);
                }
                *valuesOut = values;
                if (!mergeNullsToValues) {
                    *nullsOut = nulls;
                }
                return nulls
                           ? BooleanMix::kMix
                           : refineBooleanMixNonNull(values, activeRows);
            }
            case VectorEncoding::Simple::CONSTANT: {
                if (vector->is_null_at(0)) {
                    return BooleanMix::kAllNull;
                }
                return vector->as_unchecked<ConstantVector<bool> >()->value_at(0)
                           ? BooleanMix::kAllTrue
                           : BooleanMix::kAllFalse;
            }
            default: {
                uint64_t *nullsToSet = nullptr;
                uint64_t *valuesToSet = nullptr;
                if (vector->may_have_nulls() && !mergeNullsToValues) {
                    BaseVector::ensure_buffer<bool>(
                        size, context.pool(), tempNulls, &nullsToSet);
                    memset(nullsToSet, bits::kNotNullByte, bits::nbytes(size));
                }
                BaseVector::ensure_buffer<bool>(
                    size, context.pool(), tempValues, &valuesToSet);
                memset(valuesToSet, 0, bits::nbytes(size));
                DecodedVector decoded(*vector, activeRows);
                auto values = decoded.data<uint64_t>();
                auto nulls = decoded.nulls(&activeRows);
                auto indices = decoded.indices();
                activeRows.applyToSelected([&](int32_t i) {
                    auto index = indices[i];
                    bool isNull = nulls && bits::isBitNull(nulls, i);
                    if (!isNull && bits::isBitSet(values, index)) {
                        bits::setBit(valuesToSet, i);
                    }
                    if (nullsToSet && isNull) {
                        bits::set_null(nullsToSet, i);
                    }
                });
                if (!mergeNullsToValues) {
                    *nullsOut = nullsToSet;
                }
                *valuesOut = valuesToSet;
                return nullsToSet
                           ? BooleanMix::kMix
                           : refineBooleanMixNonNull(valuesToSet, activeRows);
            }
        }
    }
} // namespace kumo::pollux::exec
